import Defparam from '../data/defaultParams';
import Cmd from '../data/cmd';
import {SchemaError} from 'graphql-tools';

export async function createDefparam (args = {}) {
  try {
    let existCmd = await Cmd.findOne({code: args.param.code});
    if (!existCmd) {
      throw new SchemaError ('不存在对应的cmd');
    } else {
      let defparam = new Defparam (args.param);
      const res = await defparam.save ();
      console.log(res)
      return res;
    }
  } catch (err) {
    console.log (err.message);
    throw new SchemaError (err.message);
  }
}

export async function deleteDefparam (_id) {
  try {
    return await Defparam.findOneAndRemove ({_id});
  } catch (err) {
    console.log (err.message);
  }
}

export async function findDefparamList (args = {}) {
  try {
    let { page = 1, pageSize = 10 } = args;
      const query = await Defparam.find(args.params).skip((page - 1) * pageSize).limit(pageSize);
      const total = await Defparam.find(args.params);
      return {
        page: page,
        pageSize: pageSize,
        list:query,
        totalCount: total.length
      };
  } catch (err) {
    throw new SchemaError (err.message);
  }
}

export async function updateDefparam(conditions, args){
  try{
    await Defparam.findOneAndUpdate(conditions, args, {
      new: true
    });
    const res = await Defparam.findOne(args)
    return res;
  } catch (err) {
    throw new SchemaError (err.message);
  }
}
